﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using DailyDiet.Models;
using SQLite;

namespace DailyDiet.Services.Impl
{
    /// <summary>
    /// 菜品收藏
    /// </summary>
    public class FavoriteStorageService : IFavoriteStorageService {
        //******继承方法
        public const string DbName = "favorite.db";

        /// <summary>
        /// 数据库文件路径
        /// </summary>
        public static readonly string DBPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);
        /// <summary>
        /// 偏好存储
        /// </summary>
        private IPreferenceStorage _preference;

        /// <summary>
        /// 数据库连接
        /// </summary>
        private SQLiteAsyncConnection _connection;

        /// <summary>
        /// 数据库连接
        /// </summary>
        public SQLiteAsyncConnection Connection =>
            _connection ?? (_connection = new SQLiteAsyncConnection(DBPath));

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public async Task InitializeAsync() {
            await Connection.CreateTableAsync<Favorite>();
            _preference.Set(FavoriteStorageConstants.VersionKey,
                FavoriteStorageConstants.VERSION);
        }

        /// <summary>
        /// 数据库存储是否已经初始化
        /// </summary>
        /// <returns></returns>
        public bool IsInitialized() =>
            _preference
                .Get(FavoriteStorageConstants.VersionKey,
                    FavoriteStorageConstants.DEFAULTVERSION)
                .Equals(FavoriteStorageConstants.VERSION);



        public async Task<Favorite> GetFavoriteAsync(int dietId) =>
            await Connection.Table<Favorite>()
                .FirstOrDefaultAsync(p => p.DietId == dietId);

        /// <summary>
        /// 保存收藏信息
        /// </summary>
        /// <param name="favorite">收藏</param>
        /// <returns></returns>
        public async Task RefreshFavorite(Favorite favorite) =>
            await _connection.InsertOrReplaceAsync(favorite);
        
        /// <summary>
        ///获得收藏信息 
        /// </summary>
        /// <returns></returns>
        public async Task<List<Favorite>> GetFavoritesAsync() =>
            await Connection.Table<Favorite>().Where(p=>p.IsFavorite).ToListAsync();


        public async Task CloseConnection()
        {
            await _connection.CloseAsync();
            _connection = null;
        }

        /// <summary>
        /// 收藏存储
        /// </summary>
        /// <param name="preference">偏好存储</param>
        public FavoriteStorageService(IPreferenceStorage preference) {
            _preference = preference;
        }
    }
}
